<?php

declare (strict_types=1);

namespace magein\pay;

class PaySigner
{
    /**
     * 解签
     * @param array $params
     * @return bool
     */
    public function verify(array $params): bool
    {
        if (empty($params)) {
            return false;
        }

        $sign = $params['sign'] ?? '';
        if (empty($sign)) {
            return false;
        }

        unset($params['sign']);
        if ($sign == self::create($params)) {
            return true;
        }

        return false;
    }

    /**
     * 加签
     * @param array $params
     * @param string $channel_id
     * @return string
     */
    public function create(array $params, string $channel_id = ''): string
    {
        $channel_id = $channel_id ?: ($params['channel_id'] ?? '');

        // 获取签名秘钥
        if ($channel_id) {
            $secret = PayConfig::channelSecret($channel_id) ?? uniqid();
        } else {
            $secret = uniqid();
        }

        foreach ($params as $key => $val) {
            if (is_numeric($val)) {
                continue;
            }
            if (is_object($val) || is_array($val) || strlen($val) > 10000) {
                unset($params[$key]);
            }
        }

        ksort($params);
        $plain_text = '';

        foreach ($params as $key => $val) {
            $plain_text .= $key . $val;
        }

        return md5(strtolower($secret . $plain_text));
    }
}
